package team.bluepen.order.web.servlet;

import team.bluepen.order.ErrorPack;
import team.bluepen.order.constant.ErrorCode;
import team.bluepen.order.data.database.hive.OrderRepository;
import team.bluepen.order.data.database.mysql.UserRepository;
import team.bluepen.order.data.entity.Order;
import team.bluepen.order.data.entity.User;
import team.bluepen.order.util.TimeUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.StringJoiner;

/**
 * 文件下载Servlet
 * @author Kai
 */
@WebServlet(name = "FileDownloadServlet", urlPatterns = "/api/file/download")
public class FileDownloadServlet extends BaseServlet {
    public static final String TARGET_PARAM = "target";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String target = req.getParameter(TARGET_PARAM);
        setJsonHeader(resp);
        if (target == null) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_NULL, "").toCodePack());
            return;
        }

        ServletOutputStream stream = resp.getOutputStream();
        String time = TimeUtil.getTimeFormat(System.currentTimeMillis());
        String downloadName;
        if (target.equalsIgnoreCase("user")) {
            downloadName = "order_user_" + time + ".csv";
        } else if (target.equalsIgnoreCase("order")) {
            downloadName = "order_orders_" + time + ".csv";
        } else {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_DATA_NOT_EXIST,
                    "This type of data cannot be found.")
                    .toCodePack());
            return;
        }
        resp.setHeader("Content-Disposition", "attachment; filename=" + downloadName);
        resp.setContentType("application/x-download;charset=UTF-8");
        writeToStream(target, stream);

        stream.close();
        writeJson(resp, new ErrorPack(ErrorCode.SUCCESS, "SUCCESS")
                .toCodePack());

    }

    private void writeToStream(String type, ServletOutputStream stream) throws IOException {
        if (type.equals("user")) {
            UserRepository repository = new UserRepository();
            List<User> userList = repository.getUserDao().get();
            userList.forEach(user -> {
                StringJoiner joiner = new StringJoiner(",");
                joiner.add(String.valueOf(user.getId()))
                        .add(user.getUsername())
                        .add(user.getPassword())
                        .add(user.getRole().name());
                try {
                    stream.println(joiner.toString());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
        if (type.equals("order")) {
            OrderRepository repository = new OrderRepository();
            List<Order> orderList = repository.getOrderDao().get();
            orderList.forEach(order -> {
                StringJoiner joiner = new StringJoiner("\t");
                joiner.add(String.valueOf(order.getId()))
                        .add(order.getName())
                        .add(order.getDate())
                        .add(String.valueOf(order.getAmount()))
                        .add(String.valueOf(order.isValid()));
                try {
                    stream.println(joiner.toString());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }


        stream.close();
    }
}
